package com.xuebank.nfe.nfecar.wxapi

import android.app.Activity
import android.content.Intent
import android.nfc.Tag
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.wzn.libaray.event.RxBus
import com.wzn.libaray.utils.Logger
import com.xuebank.nfe.nfecar.MainActivity
import com.xuebank.nfe.nfecar.R
import com.xuebank.nfe.nfecar.globals.Constants
import com.xuebank.nfe.nfecar.model.JSEvent

class WXEntryActivity : Activity(), IWXAPIEventHandler {
    private var code: String? = null
    public var wx_api: IWXAPI? = null
    private var date: JSEvent? = null
    override fun onResp(resp: BaseResp?) {
        when (resp?.errCode) {
            BaseResp.ErrCode.ERR_OK -> {
                Log.i("WXTest", "onResp OK")
                if (resp is SendAuth.Resp) {
                     //获取微信传回的code
                    code = resp.code
                    date = JSEvent(code?:"")
                    RxBus.getDefault().post(date)
                    Log.i("从微信获取的code", "onResp code = " + code)


                    Toast.makeText(this,"onResp code = " + code,Toast.LENGTH_SHORT).show()
                }
            }
            //发送取消
            BaseResp.ErrCode.ERR_USER_CANCEL ->{
                RxBus.getDefault().post(Constants.WECHAT_SEND_CANCEL)
                Log.i("WXTest", "onResp ERR_USER_CANCEL ")
            }

            //发送被拒绝
            BaseResp.ErrCode.ERR_AUTH_DENIED ->{
                RxBus.getDefault().post(Constants.WECHAT_AUTH_DENIED)
                Log.i("WXTest", "onResp ERR_AUTH_DENIED")
            }
            //发送返回
            else ->{
                RxBus.getDefault().post(Constants.WECHAT_DEFAULT_ERRCODE)

                Log.i("WXTest", "onResp default errCode " + resp?.errCode)
            }
        }


        finish()
    }

    override fun onReq(p0: BaseReq?) {
        Log.i("WXTest", "onResp OK")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_wxentry)
        wx_api = WXAPIFactory.createWXAPI(this, Constants.WECHAT_APP_ID, false);
        wx_api?.handleIntent(getIntent(), this);
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        wx_api?.handleIntent(intent, this@WXEntryActivity)//必须调用此句话
        finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        wx_api?.handleIntent(data,this)
    }


}
